package cn.xyfmzmy.chain.validation;

import cn.xyfmzmy.chain.annotation.Length;
import cn.xyfmzmy.chain.annotation.Max;
import cn.xyfmzmy.chain.annotation.Min;
import cn.xyfmzmy.chain.exception.ValidationException;

import java.lang.reflect.Field;

/**
 * 校验器
 */
public class Validator {

    // 校验方法
    public void validate(Object bean) throws Exception {
        // 利用反射，遍历bean的所有属性
        Class<?> beanClass = bean.getClass();
        Field[] declaredFields = beanClass.getDeclaredFields();
        for(Field field : declaredFields){
            field.setAccessible(true);
            // 每个属性，都有自己的一个校验链
            ValidateChain validateChain = buildValidateChain(field);
            try {
                validateChain.validate(field.get(bean));
            } catch (ValidationException exception){
                exception.printStackTrace();
            }
        }
    }

    private ValidateChain buildValidateChain(Field field) {
        ValidateChain validateChain = new ValidateChain();
        Max max = field.getAnnotation(Max.class);
        if(max != null){
            validateChain.addLastHandler(new MaxValidateHandler(max.value()));
        }
        Min min = field.getAnnotation(Min.class);
        if(min != null){
            validateChain.addLastHandler(new MinValidateHandler(min.value()));
        }
        Length length = field.getAnnotation(Length.class);
        if(length != null){
            validateChain.addLastHandler(new LengthValidateHandler(length.value()));
        }
        return validateChain;
    }
}
